﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Net;
using System.ComponentModel;
using Org.BouncyCastle.OpenSsl;
using System.IO;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Math;
using Sicurezza.Entita;

namespace Sicurezza.Client.Manager
{
    

    public class ValidityManager
    {
        public static event EventHandler VerifyReceived;

        private static bool OCSP = Convert.ToBoolean(ConfigurationManager.AppSettings["OCSP"]);
        private static string crlURL = ConfigurationManager.AppSettings["crlURL"];
        private static string crlFile = ConfigurationManager.AppSettings["crlFile"];

        private static int CertificateSerial;

        public static void Validate(int serial)
        {
            if (OCSP)
                ValidateByOcsp(serial);
            else
                ValidateByCrl(serial);
        }

        private static void ValidateByCrl(int serial)
        {
            CertificateSerial = serial;

            if(File.Exists(crlFile))
                File.Delete(crlFile);
            // Create an instance of WebClient
            WebClient client = new WebClient();

            // Hookup DownloadFileCompleted Event
            client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(client_DownloadFileCompleted);

            // Start the download and copy the file to c:\temp
            client.DownloadFileAsync(new Uri(crlURL), crlFile);

        }

        private static void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            
            PemReader pr = new PemReader(File.OpenText(crlFile));
            X509Crl crl = (X509Crl)pr.ReadObject();
            X509CrlEntry entry = crl.GetRevokedCertificate(new BigInteger(CertificateSerial.ToString()));
            if (entry != null)
            {
                if(VerifyReceived!=null)
                    VerifyReceived(OCSPResult.Revoked, null);
            }
            else
            {
                if (VerifyReceived != null)
                    VerifyReceived(OCSPResult.Valid, null);
            }
              

        }

        private static void ValidateByOcsp(int serial)
        {
            string state = WSManager.ValidateByOcsp(serial);
            OCSPResult result = (OCSPResult)Enum.Parse(typeof(OCSPResult), state, true);
            if (VerifyReceived != null)
                VerifyReceived(result, null);

        }
    }
}
